package baidu_uid

import (
	"errors"
	"math/bits"
	"sync"
)

const (
	START_POINT = -1

	// 增长因子
	DEFAULT_PADDING_PERCENT = 50
)

type RingBuffer struct {
	lock *sync.Mutex

	// 当前指针 和 尾指针
	cursor int32
	tail   int32

	paddingThreshold int32
	bufferSize       int32
	indexMask        int32
}

func NewRingBufferDefault(bufferSize int32) (*RingBuffer, error) {
	return NewRingBuffer(bufferSize, DEFAULT_PADDING_PERCENT)
}

// NewRingBuffer
//
//	Constructor with buffer size & padding factor
//
//	@param bufferSize must be positive & a power of 2
//	@param paddingFactor percent in (0 - 100). When the count of rest available UIDs reach the threshold, it will trigger padding buffer<br>
//	       Sample: paddingFactor=20, bufferSize=1000 -> threshold=1000 * 20 /100,
//	       padding buffer will be triggered when tail-cursor<threshold
func NewRingBuffer(bufferSize int32, paddingFactor int32) (*RingBuffer, error) {
	// check buffer size is positive & a power of 2; padding factor in (0, 100)

	// RingBuffer的尺寸是2^n，n必须是正整数
	if bufferSize <= 0 {
		return nil, errors.New("RingBuffer size must be positive")
	}

	if bits.OnesCount32(uint32(bufferSize)) != 1 {
		return nil, errors.New("RingBuffer size must be a power of 2")
	}

	if paddingFactor <= 0 || paddingFactor >= 100 {
		return nil, errors.New("paddingFactor  must between  0 and 100")
	}

	return &RingBuffer{
		lock:             &sync.Mutex{},
		bufferSize:       bufferSize,
		indexMask:        bufferSize - 1,
		paddingThreshold: bufferSize * paddingFactor / 100,
	}, nil

}

func (rb *RingBuffer) Put(uid int64) {
	rb.lock.Lock()
	defer rb.lock.Unlock()

}

func (rb *RingBuffer) Take() {
	rb.lock.Lock()
	defer rb.lock.Unlock()

}
